#!/usr/bin/python
import pexpect
import os
import sys
import pp
import time
def expectandshow(child, expect):
        index=child.expect(expect)
        print child.before,child.after,
        return index

def set_(ip):
	HOSTNAME=ip
        NETWORKING="yes"
        NETWORKING_IPV6="no"
	password="passw0rd"

	NISNAME="SecondPaaS"

        cmd = "ssh root@" + ip+ " echo \'" + "NETWORKING="+NETWORKING+"\' > /etc/sysconfig/network;" \
                + "echo \'NETWORKING_IPV6=" + NETWORKING_IPV6 + "\' >> /etc/sysconfig/network ;" \
                + "echo \'HOSTNAME=" + HOSTNAME + "\' >> /etc/sysconfig/network; "\
                + "echo \'NISDOMAIN=" + NISNAME + "\' >> /etc/sysconfig/network"
        print cmd


        scp_child=pexpect.spawn(cmd)
        index=expectandshow(scp_child, \
                                ['Are you sure you want to continue connecting', \
                                "root@"+ip+"'s password:", \
                                pexpect.TIMEOUT, \
                                pexpect.EOF])
        if index == 0:
                scp_child.sendline('yes')
                ret = expectandshow(scp_child, ["root@"+ip+"'s password:", pexpect.EOF])
                if ret == 0:
                        scp_child.sendline(password)
                        expectandshow(scp_child, [pexpect.EOF])
                elif ret == 1:
                        pass
        elif index == 1:
                scp_child.sendline(password)
                expectandshow(scp_child, [pexpect.EOF])
        elif index == 2:
                print "timeout, ignore and continue."
        elif index == 3:
                pass


order=[]

path=sys.path[0]

fp_intr = open(path+'/ip','r')
total_ip = 0
while True:
        line = fp_intr.readline()
        length = len(line)

        if length == 0: # Zero length indicates EOF
                break
	total_ip += 1
        line=line[0:length-1]
        print line
        order.append(line)
fp_intr.close();
#total_ip = 1
start_time = time.time()

ppservers = ()

job_server = pp.Server(total_ip, ppservers=ppservers)

print "Starting pp with", job_server.get_ncpus(), "workers"

jobs = []

for ip in order:
    	jobs.append(job_server.submit(set_, (ip,), (expectandshow,), ("pexpect",)))


	
for job in jobs:
    job()

print "Time elapsed: ", time.time() - start_time, "s"

job_server.print_stats()








#NETWORKING=yes
#NETWORKING_IPV6=no
#HOSTNAME=192.168.226.192
#NISDOMAIN=PaaSMPI
